package com.nursinghome.management.service;

import com.nursinghome.management.model.Elderly;
import com.nursinghome.management.model.Medication;
import com.nursinghome.management.repository.MedicationRepository;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class MedicationService {

    private final MedicationRepository medicationRepository;

    public MedicationService(MedicationRepository medicationRepository) {
        this.medicationRepository = medicationRepository;
    }

    public List<Medication> getAllMedications() {
        return medicationRepository.findAll();
    }

    public Medication getMedicationById(Long id) {
        return medicationRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Medication not found with id: " + id));
    }

    public List<Medication> getActiveMedicationsByElderly(Elderly elderly) {
        return medicationRepository.findByElderlyAndActiveTrue(elderly);
    }

    public Medication createMedication(Medication medication) {
        return medicationRepository.save(medication);
    }

    public Medication updateMedication(Medication medication) {
        Medication existingMedication = medicationRepository.findById(medication.getId())
                .orElseThrow(() -> new RuntimeException("Medication not found with id: " + medication.getId()));

        existingMedication.setName(medication.getName());
        existingMedication.setDosage(medication.getDosage());
        existingMedication.setFrequency(medication.getFrequency());
        existingMedication.setMorningTime(medication.getMorningTime());
        existingMedication.setAfternoonTime(medication.getAfternoonTime());
        existingMedication.setEveningTime(medication.getEveningTime());
        existingMedication.setNightTime(medication.getNightTime());
        existingMedication.setStartDate(medication.getStartDate());
        existingMedication.setEndDate(medication.getEndDate());
        existingMedication.setInstructions(medication.getInstructions());
        existingMedication.setPrescribedBy(medication.getPrescribedBy());
        existingMedication.setActive(medication.isActive());

        return medicationRepository.save(existingMedication);
    }

    public void deleteMedication(Long id) {
        medicationRepository.deleteById(id);
    }
}